package uoc.biblioteca.mappings.dao;

// Generated 11/04/2011 14:10:24 by Hibernate Tools 3.2.1.GA

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.sun.org.apache.regexp.internal.recompile;

import uoc.biblioteca.mappings.object.EstadoSolicitudVo;
import uoc.biblioteca.mappings.object.LlibreVo;
import uoc.biblioteca.mappings.object.SolicitudLlibreVo;
import uoc.biblioteca.sessionFactory.HibernateSessionFactory;

/**
 * Home object for domain model class SolicitudLlibre.
 * @see uoc.biblioteca.mappings.dao.SolicitudLlibreVo
 * @author Hibernate Tools
 */
public class SolicitudLlibreHome extends BaseHome {

	private static final Log log = LogFactory.getLog(SolicitudLlibreHome.class);

	private final SessionFactory sessionFactory = null;


	public SolicitudLlibreVo findById(java.lang.Integer id) {
		log.debug("getting SolicitudLlibreVo instance with id: " + id);
		try {
			
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			SolicitudLlibreVo instance = (SolicitudLlibreVo) session.get("uoc.biblioteca.mappings.object.SolicitudLlibreVo", id);
			if (instance == null) {
				log.debug("get successful, no instance found");
			} else {
				log.debug("get successful, instance found");
				instance.getLlibre();
				instance.getUser();
				instance.getEstadoSolicitud();
			}
			
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public void saveNew(SolicitudLlibreVo instance) {
		
		log.debug("save new SolicitudLlibreVo instance");
		
		try {
			
			Date dataNow = new Date();
			instance.setDataActualizacio(dataNow);
			
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();
			
			session.clear();
			
			tx = session.beginTransaction();
			
			session.saveOrUpdate(instance);
			
			tx.commit();
			session.close();
			
			log.debug("saveNew successful");
			
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	//Mostrar todos los libros solicitados menos los anulados por el usuario
	public SolicitudLlibreVo[] getAllSolicitudsLlibre(String idSolicitud,Integer idUser) {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudLlibreVo as c where c.user.id = "+idUser;
			
			if(idSolicitud!=null){
				hql+=" and c.estadoSolicitud.idEstadoSolicitud = "+idSolicitud;
			}
			hql += " order by c.dataCreacio desc";
			
			
			//String hql= "select c from SolicitudLlibre as c where c.estadoSolicitud.idEstadoSolicitud != "+ID_ANULAT+" order by c.idSolicitud";
			//String hql= "select c from SolicitudLlibre as c order by c.idSolicitud";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudLlibreVo solicitudTemp = (SolicitudLlibreVo) iter.next();
				solicitudTemp.getLlibre();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudLlibreVo[]) solicituds.toArray(new SolicitudLlibreVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//Mostrar todos los libros solicitados noves para gestion
	public SolicitudLlibreVo[] getAllSolicitudsLlibreNoves() {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudLlibreVo as c where c.estadoSolicitud.idEstadoSolicitud = 1";
			
			hql += " order by c.dataCreacio asc";
			
			
			//String hql= "select c from SolicitudLlibre as c where c.estadoSolicitud.idEstadoSolicitud != "+ID_ANULAT+" order by c.idSolicitud";
			//String hql= "select c from SolicitudLlibre as c order by c.idSolicitud";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudLlibreVo solicitudTemp = (SolicitudLlibreVo) iter.next();
				solicitudTemp.getLlibre();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudLlibreVo[]) solicituds.toArray(new SolicitudLlibreVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//Mostrar todos los libros solicitados 
	public SolicitudLlibreVo[] getAllSolicitudsLlibre() {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudLlibreVo as c";
			
			hql += " order by c.dataCreacio desc";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudLlibreVo solicitudTemp = (SolicitudLlibreVo) iter.next();
				solicitudTemp.getLlibre();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudLlibreVo[]) solicituds.toArray(new SolicitudLlibreVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//Mostrar todos los libros solicitados con filtros (historics)
	public SolicitudLlibreVo[] getAllSolicitudsLlibreByFiltres(String idEstado,boolean totsTipus,boolean checkBr,boolean checkGrup,boolean checkRecer,boolean checkDes,Date dataInici,Date dataFi) {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			boolean isOr=false;
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudLlibreVo as c where 1=1";
			if(idEstado!=null && !idEstado.equals("0")){
				hql += " and c.estadoSolicitud.idEstadoSolicitud="+idEstado;
			}
			if(!totsTipus){
				if(checkBr){
					if(!isOr){
						hql += " and ( c.tipusSolicitud=1 ";
						isOr=true;
					}
					else{
						hql += " or c.tipusSolicitud=1 ";
					}
					
				}
				if(checkGrup){
					if(!isOr){
						hql += " and ( c.tipusSolicitud=2 ";
						isOr=true;
					}
					else{
						hql += " or c.tipusSolicitud=2 ";
					}
					
				}
				if(checkRecer){
					if(!isOr){
						hql += " and ( c.tipusSolicitud=3 ";
						isOr=true;
					}
					else{
						hql += " or c.tipusSolicitud=3 ";
					}
				}
				if(checkDes){
					if(!isOr){
						hql += " and ( c.tipusSolicitud=4 ";
						isOr=true;
					}
					else{
						hql += " or c.tipusSolicitud=4 ";
					}
				}
				if(isOr){
					hql += ") ";
				}
			}
			
			if(dataInici!=null){
				//hql += " and c.dataCreacio>"+dataInici;
				hql += " and c.dataCreacio>= :dataInici";
				
			}
			if(dataFi!=null){
				//hql += " and c.dataCreacio<"+dataFi;
				hql += " and c.dataCreacio<= :dataFi";
				
			}
			
			
			hql += " order by c.dataCreacio desc";
			
			List tmpEvents = null;
			
			if(dataInici!=null && dataFi ==null){
				tmpEvents = session.createQuery(hql).setDate("dataInici", dataInici).list(); 
			}
			else if(dataFi!=null && dataInici ==null ){
				tmpEvents = session.createQuery(hql).setDate("dataFi", dataFi).list(); 
			}
			else if(dataInici !=null && dataFi!=null ){
				tmpEvents = session.createQuery(hql).setDate("dataInici", dataInici).setDate("dataFi", dataFi).list(); 
			}
			else{
				tmpEvents = session.createQuery(hql).list();
			}
			
			//String hql = "select * from Book as b where b.releaseDate > :date1 and b.releaseDate < :date2"; 
			//session.createQuery(hql).setDate("date1", date1).setDate("date2", date2).list(); 
			
			
			
			//List tmpEvents = session.createQuery(hql).list();
			
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudLlibreVo solicitudTemp = (SolicitudLlibreVo) iter.next();
				solicitudTemp.getLlibre();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudLlibreVo[]) solicituds.toArray(new SolicitudLlibreVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	//Mostrar todos los libros solicitados per filtres (mis solicituds propias y altres)
	public SolicitudLlibreVo[] getAllSolicitudsLlibreByFiltres(String idEstado,boolean totsTipus,boolean checkBr,boolean checkGrup,boolean checkRecer,boolean checkDes,Date dataInici,Date dataFi,Integer idUser,String nickUser,String titolFiltre) {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			
			boolean isOr=false;
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudLlibreVo as c  where 1=1 ";
			
			//Si se filtra por el usuario (mis solicitudes)
			if(idUser!=null || nickUser!=null){
				
				if(titolFiltre!=null && !("").equals(titolFiltre)){
					hql+=" and c.llibre.titol LIKE '%"+titolFiltre+"%'" ;
				}
				
				
				//hql+=" where (c.user.id = "+idUser +" or c.personaSolicitant='"+nameUser+ "') " ;
				if(idUser!=null){
					hql+=" and c.user.id = "+idUser ;
				}
				else if(nickUser!=null){
					hql+=" and c.personaSolicitant='"+nickUser+"' and c.user.nick!='"+nickUser+"'";
				}
				
				if(idEstado!=null && !idEstado.equals("0")){
					hql += " and c.estadoSolicitud.idEstadoSolicitud="+idEstado;
				}
				if(!totsTipus){
					if(checkBr){
						if(!isOr){
							hql += " and ( c.tipusSolicitud=1 ";
							isOr=true;
						}
						else{
							hql += " or c.tipusSolicitud=1 ";
						}
						
					}
					if(checkGrup){
						if(!isOr){
							hql += " and ( c.tipusSolicitud=2 ";
							isOr=true;
						}
						else{
							hql += " or c.tipusSolicitud=2 ";
						}
						
					}
					if(checkRecer){
						if(!isOr){
							hql += " and ( c.tipusSolicitud=3 ";
							isOr=true;
						}
						else{
							hql += " or c.tipusSolicitud=3 ";
						}
					}
					if(checkDes){
						if(!isOr){
							hql += " and ( c.tipusSolicitud=4 ";
							isOr=true;
						}
						else{
							hql += " or c.tipusSolicitud=4 ";
						}
					}
					if(isOr){
						hql += ") ";
					}
				}
				
				if(dataInici!=null){
					//hql += " and c.dataCreacio>"+dataInici;
					hql += " and c.dataCreacio>= :dataInici";
					
				}
				if(dataFi!=null){
					//hql += " and c.dataCreacio<"+dataFi;
					hql += " and c.dataCreacio<= :dataFi";
					
				}
			}
			
			else{
				//Si no se filtra por el usuario
				
				if(titolFiltre!=null && !("").equals(titolFiltre)){
					hql+=" and c.llibre.titol LIKE '%"+titolFiltre+"%'" ;
				}
				
				if(idEstado!=null && !idEstado.equals("0")){
					hql += " and c.estadoSolicitud.idEstadoSolicitud="+idEstado;
				}
				if(!totsTipus){
					if(checkBr){
						if(!isOr){
							hql += " and ( c.tipusSolicitud=1 ";
							isOr=true;
						}
						else{
							hql += " or c.tipusSolicitud=1 ";
						}
						
					}
					if(checkGrup){
						if(!isOr){
							hql += " and ( c.tipusSolicitud=2 ";
							isOr=true;
						}
						else{
							hql += " or c.tipusSolicitud=2 ";
						}
						
					}
					if(checkRecer){
						if(!isOr){
							hql += " and ( c.tipusSolicitud=3 ";
							isOr=true;
						}
						else{
							hql += " or c.tipusSolicitud=3 ";
						}
					}
					if(checkDes){
						if(!isOr){
							hql += " and ( c.tipusSolicitud=4 ";
							isOr=true;
						}
						else{
							hql += " or c.tipusSolicitud=4 ";
						}
					}
					if(isOr){
						hql += ") ";
					}
				}
				
				if(dataInici!=null){
					//hql += " and c.dataCreacio>"+dataInici;
					hql += " and c.dataCreacio>= :dataInici";
					
				}
				if(dataFi!=null){
					//hql += " and c.dataCreacio<"+dataFi;
					hql += " and c.dataCreacio<= :dataFi";
					
				}
				
			}
			
			hql += " order by c.dataActualizacio desc";
			
			List tmpEvents = null;
			
			if(dataInici!=null && dataFi ==null){
				tmpEvents = session.createQuery(hql).setDate("dataInici", dataInici).list(); 
			}
			else if(dataFi!=null && dataInici ==null ){
				tmpEvents = session.createQuery(hql).setDate("dataFi", dataFi).list(); 
			}
			else if(dataInici !=null && dataFi!=null ){
				tmpEvents = session.createQuery(hql).setDate("dataInici", dataInici).setDate("dataFi", dataFi).list(); 
			}
			else{
				tmpEvents = session.createQuery(hql).list();
			}
			
			
			//List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudLlibreVo solicitudTemp = (SolicitudLlibreVo) iter.next();
				solicitudTemp.getLlibre();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudLlibreVo[]) solicituds.toArray(new SolicitudLlibreVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//Mostrar todos los libros duplicados por titol 
	public SolicitudLlibreVo[] getDuplicatsSolicitudsLlibre(LlibreVo llibre) {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudLlibreVo as c where c.llibre.titol = '"+llibre.getTitol().replaceAll("'", "")+"' or c.llibre.isbn ='"+llibre.getIsbn()+"' ";
			hql += " order by c.dataCreacio asc";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudLlibreVo solicitudTemp = (SolicitudLlibreVo) iter.next();
				solicitudTemp.getLlibre();
				solicitudTemp.getEstadoSolicitud();
				solicitudTemp.getUser();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudLlibreVo[]) solicituds.toArray(new SolicitudLlibreVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//Mostrar todos los libros para exportar a Millenium 
	public List getSolicitudsLlibreToMillenium() {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudLlibreVo as c where c.enviadaMill=0 and c.validadoGestor=1 and c.tratadoMillenium = 0 and c.estadoSolicitud.idEstadoSolicitud=1";
			hql += " order by c.dataCreacio asc";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudLlibreVo solicitudTemp = (SolicitudLlibreVo) iter.next();
				solicitudTemp.getLlibre();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return solicituds;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public SolicitudLlibreVo duplicarSolicitud(SolicitudLlibreVo solLlibre) {
		
		SolicitudLlibreVo solLlibreNew = new SolicitudLlibreVo();
		
		try{
			Date dateNow = new Date();
			
			if(solLlibre!=null){
				solLlibreNew.setAssignatura(solLlibre.getAssignatura());
				solLlibreNew.setCentreResponsabilitat(solLlibre.getCentreResponsabilitat());
				solLlibreNew.setCodiOsrt(solLlibre.getCodiOsrt());
				solLlibreNew.setCodiProyecte(solLlibre.getCodiProyecte());
				solLlibreNew.setDataActualizacio(dateNow);
				solLlibreNew.setDataCreacio(dateNow);
				EstadoSolicitudVo estado = new EstadoSolicitudVo();
				estado.setIdEstadoSolicitud(1);
				solLlibreNew.setEstadoSolicitud(estado);
				solLlibreNew.setIdPerfilUoc(solLlibre.getIdPerfilUoc());
				solLlibreNew.setLlibre(solLlibre.getLlibre());
				solLlibreNew.setNomGrupOrganitzatiu(solLlibre.getNomGrupOrganitzatiu());
				solLlibreNew.setNregistroBiblio(solLlibre.getNregistroBiblio());
				solLlibreNew.setNregistroMillenium(null);
				solLlibreNew.setPersonaSolicitant(solLlibre.getPersonaSolicitant());
				solLlibreNew.setTipusSolicitud(solLlibre.getTipusSolicitud());
				solLlibreNew.setUser(solLlibre.getUser());
				solLlibreNew.setValidadoGestor(0);
				solLlibreNew.setIdSolicitud(null);
				
				saveNew(solLlibreNew);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return solLlibreNew;
		
	}
	
	//Mostrar el numero de libros sin ISBN para exportar a Millenium 
	public int comprobaSolicitudsLlibreToMilleniumSinIsbn() {
		
		/* will hold the books we are going to return later */
		try{
			int i=0;
			
		
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudLlibreVo as c where c.enviadaMill=0 and c.validadoGestor=1 and c.tratadoMillenium = 0 and c.estadoSolicitud.idEstadoSolicitud=1";
			hql += " order by c.dataCreacio asc";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudLlibreVo solicitudTemp = (SolicitudLlibreVo) iter.next();
				solicitudTemp.getLlibre();
				
				if(solicitudTemp.getLlibre().getIsbn()==null || solicitudTemp.getLlibre().getIsbn().equals("")){
					i++;
				}
				
			}
			tx.commit();
			
			return i;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	//Mostrar el numero de libros para exportar a Millenium sin validar por el gestor 
	public int comprobaSolicitudsLlibreToMilleniumSinValidar() {
		
		/* will hold the books we are going to return later */
		try{
			Integer i=0;
			
		
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select count(c) from uoc.biblioteca.mappings.object.SolicitudLlibreVo as c where c.enviadaMill=0 and c.validadoGestor=0 and c.tratadoMillenium = 0 and c.estadoSolicitud.idEstadoSolicitud=1";
			hql += " order by c.dataCreacio asc";
			
			i = (Integer) session.createQuery(hql).uniqueResult();
			
			tx.commit();
			
			return i;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}


}
